#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import click
import logging
import json
from tornado import ioloop
from dmz_relay.relay import Relay
from dmz_relay.query import Query

click.disable_unicode_literals_warning = True

RELAY_PORT = 2333
RELAY_HTTP = 8080
QUERY_PORT = 80


def read_config(ctx, param, value):
    if not value:
        return {}
    import json

    def underline_dict(d):
        if not isinstance(d, dict):
            return d
        return dict(
            (k.replace('-', '_'), underline_dict(v)) for k, v in d.items())

    config = underline_dict(json.load(value))
    ctx.default_map = config
    return config


@click.group(invoke_without_command=True)
@click.option('-c', '--config', callback=read_config, type=click.File('r'))
@click.option('--debug', default=False, is_flag=True, help='debug mode')
@click.pass_context
def cli(ctx, **kwargs):
    logging.basicConfig(level=logging.DEBUG if kwargs["debug"] else logging.INFO)
    ctx.obj = ctx.obj or {}
    ctx.obj.update(kwargs)
    return ctx


@cli.command(help="run as relay")
@click.option('-h', '--http', default=RELAY_HTTP, help="listen port for http request")
@click.option('-p', '--port', default=RELAY_PORT, help="listen port for dmz client")
@click.pass_context
def relay(ctx, http, port):
    io_loop = ioloop.IOLoop.current()
    r = Relay(relay_port=port, http_port=http, io_loop=io_loop)
    io_loop.start()


@cli.command(help="run as query")
@click.option('--log-path', default="")
@click.option('--relay-host', default="127.0.0.1", help="relay server host")
@click.option('--relay-port', default=RELAY_PORT, help="relay server port")
@click.option('--query-server', default="http://127.0.0.1", help="query server url")
@click.option('--result-server', default="http://127.0.0.1", help="result server url")
@click.option('--num-workers', default=10, help="query worker num")
@click.option('--header', default=False, is_flag=True, help='http send header')
@click.pass_context
def query(ctx, log_path, relay_host, relay_port, query_server, result_server, num_workers, header):
    import os
    if log_path and not os.path.exists(log_path):
        os.makedirs(log_path)
    io_loop = ioloop.IOLoop.current()
    q = Query(log_path, relay_host, relay_port, query_server, result_server, num_workers, header,
              io_loop)
    q.start_tunnel()
    io_loop.start()


if __name__ == '__main__':
    cli()
